<template>
  <view class="container">
    <!-- 导航栏 -->
    <view class="nav-bar">
      <button class="back-btn" @click="goBack">返回</button>
      <text class="title">电子围栏</text>
      <button class="save-btn" @click="saveFence">保存</button>
    </view>

    <!-- 宠物选择 -->
    <view class="pet-section">
      <view class="section-title">选择宠物</view>
      <picker 
        :value="petIndex" 
        :range="pets" 
        range-key="name"
        @change="onPetChange"
        class="pet-picker"
      >
        <view class="picker-content">
          <image 
            :src="selectedPet.photo || '/static/img/default-pet.png'" 
            class="pet-avatar"
            mode="aspectFill"
          ></image>
          <text class="pet-name">{{ selectedPet.name || '请选择宠物' }}</text>
          <text class="picker-arrow">▼</text>
        </view>
      </picker>
    </view>

    <!-- 地图容器 -->
    <view class="map-container">
      <map 
        :latitude="mapCenter.latitude" 
        :longitude="mapCenter.longitude"
        :markers="markers"
        :circles="circles"
        :scale="15"
        :show-location="true"
        class="map"
        @tap="onMapTap"
      ></map>
    </view>

    <!-- 围栏设置 -->
    <view class="fence-section">
      <view class="section-title">围栏设置</view>
      
      <view class="form-item">
        <text class="label">围栏名称</text>
        <input 
          v-model="fenceData.name" 
          placeholder="请输入围栏名称" 
          class="input"
          maxlength="50"
        />
      </view>

      <view class="form-item">
        <text class="label">中心位置</text>
        <view class="coords-display">
          <text class="coord-text">经度: {{ fenceData.centerLongitude || '点击地图选择' }}</text>
          <text class="coord-text">纬度: {{ fenceData.centerLatitude || '点击地图选择' }}</text>
        </view>
      </view>

      <view class="form-item">
        <text class="label">围栏半径 (米)</text>
        <slider 
          :value="fenceData.radius" 
          :min="50" 
          :max="5000" 
          :step="50"
          @change="onRadiusChange"
          class="radius-slider"
        />
        <text class="radius-value">{{ fenceData.radius }}米</text>
      </view>

      <view class="form-item">
        <text class="label">启用状态</text>
        <switch 
          :checked="fenceData.enabled" 
          @change="onEnabledChange"
          color="#007AFF"
        />
      </view>

      <view class="form-item">
        <text class="label">报警设置</text>
        <view class="alarm-options">
          <view class="alarm-option" @click="toggleAlarm('enter')">
            <text class="option-text">进入围栏报警</text>
            <switch 
              :checked="fenceData.enterAlarm" 
              @change="onEnterAlarmChange"
              color="#007AFF"
            />
          </view>
          <view class="alarm-option" @click="toggleAlarm('exit')">
            <text class="option-text">离开围栏报警</text>
            <switch 
              :checked="fenceData.exitAlarm" 
              @change="onExitAlarmChange"
              color="#007AFF"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- 围栏列表 -->
    <view class="fence-list" v-if="fenceList.length > 0">
      <view class="section-title">现有围栏</view>
      <view 
        class="fence-item" 
        v-for="fence in fenceList" 
        :key="fence.id"
      >
        <view class="fence-info">
          <text class="fence-name">{{ fence.name }}</text>
          <text class="fence-radius">半径: {{ fence.radius }}米</text>
          <text class="fence-status" :class="getStatusClass(fence.enabled)">
            {{ fence.enabled ? '已启用' : '已禁用' }}
          </text>
        </view>
        <view class="fence-actions">
          <button class="action-btn edit" @click="editFence(fence)">编辑</button>
          <button class="action-btn delete" @click="deleteFence(fence.id)">删除</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      pets: [],
      selectedPet: null,
      petIndex: -1,
      mapCenter: {
        latitude: 39.9042,
        longitude: 116.4074
      },
      markers: [],
      circles: [],
      fenceData: {
        name: '',
        centerLongitude: null,
        centerLatitude: null,
        radius: 500,
        enabled: true,
        enterAlarm: true,
        exitAlarm: true
      },
      fenceList: [],
      baseUrl: 'http://localhost:8080/dev-api/api'
    }
  },
  onLoad() {
    this.loadPets()
    this.loadFenceList()
  },
  methods: {
    async loadPets() {
      try {
        const response = await uni.request({
          url: `${this.baseUrl}/pets/user/1`,
          method: 'GET'
        })
        
        if (response.statusCode === 200) {
          this.pets = response.data
          if (this.pets.length > 0) {
            this.selectedPet = this.pets[0]
          }
        }
      } catch (error) {

      }
    },
    
    async loadFenceList() {
      try {
        const response = await uni.request({
          url: `${this.baseUrl}/fence/user/1`,
          method: 'GET'
        })
        
        if (response.statusCode === 200) {
          this.fenceList = response.data
        }
      } catch (error) {

      }
    },
    
    onPetChange(e) {
      this.petIndex = e.detail.value
      this.selectedPet = this.pets[this.petIndex]
    },
    
    onMapTap(e) {
      const { latitude, longitude } = e.detail
      this.fenceData.centerLatitude = latitude
      this.fenceData.centerLongitude = longitude
      this.updateMapMarkers()
      this.updateMapCircles()
    },
    
    updateMapMarkers() {
      if (this.fenceData.centerLatitude && this.fenceData.centerLongitude) {
        this.markers = [{
          id: 1,
          latitude: this.fenceData.centerLatitude,
          longitude: this.fenceData.centerLongitude,
          title: '围栏中心',
          iconPath: '/static/img/marker-center.png',
          width: 30,
          height: 30
        }]
      }
    },
    
    updateMapCircles() {
      if (this.fenceData.centerLatitude && this.fenceData.centerLongitude) {
        this.circles = [{
          latitude: this.fenceData.centerLatitude,
          longitude: this.fenceData.centerLongitude,
          radius: this.fenceData.radius,
          color: '#007AFF',
          fillColor: '#007AFF',
          fillOpacity: 0.1,
          strokeWidth: 2
        }]
      }
    },
    
    onRadiusChange(e) {
      this.fenceData.radius = e.detail.value
      this.updateMapCircles()
    },
    
    onEnabledChange(e) {
      this.fenceData.enabled = e.detail.value
    },
    
    onEnterAlarmChange(e) {
      this.fenceData.enterAlarm = e.detail.value
    },
    
    onExitAlarmChange(e) {
      this.fenceData.exitAlarm = e.detail.value
    },
    
    toggleAlarm(type) {
      // 切换报警设置
    },
    
    getStatusClass(enabled) {
      return enabled ? 'status-enabled' : 'status-disabled'
    },
    
    editFence(fence) {
      this.fenceData = { ...fence }
      this.updateMapMarkers()
      this.updateMapCircles()
    },
    
    deleteFence(fenceId) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个围栏吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const response = await uni.request({
                url: `${this.baseUrl}/fence/${fenceId}`,
                method: 'DELETE'
              })
              
              if (response.statusCode === 200) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                this.loadFenceList()
              }
            } catch (error) {
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    validateForm() {
      if (!this.selectedPet) {
        uni.showToast({
          title: '请选择宠物',
          icon: 'none'
        })
        return false
      }
      
      if (!this.fenceData.name.trim()) {
        uni.showToast({
          title: '请输入围栏名称',
          icon: 'none'
        })
        return false
      }
      
      if (!this.fenceData.centerLatitude || !this.fenceData.centerLongitude) {
        uni.showToast({
          title: '请在地图上选择围栏中心点',
          icon: 'none'
        })
        return false
      }
      
      return true
    },
    
    async saveFence() {
      if (!this.validateForm()) {
        return
      }
      
      uni.showLoading({
        title: '保存中...'
      })
      
      try {
        const submitData = {
          ...this.fenceData,
          petId: this.selectedPet.id,
          userId: 1
        }
        
        const res = await uni.request({
          url: `${this.baseUrl}/fence`,
          method: 'POST',
          data: submitData
        })
        
        uni.hideLoading()
        
        if (res.statusCode === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          
          this.loadFenceList()
          this.resetForm()
        } else {
          uni.showToast({
            title: '保存失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    },
    
    resetForm() {
      this.fenceData = {
        name: '',
        centerLongitude: null,
        centerLatitude: null,
        radius: 500,
        enabled: true,
        enterAlarm: true,
        exitAlarm: true
      }
      this.markers = []
      this.circles = []
    },
    
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
.container {
  background: #f5f5f5;
  min-height: 100vh;
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.back-btn, .save-btn {
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 10rpx 30rpx;
  font-size: 28rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
}

.pet-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.pet-picker {
  width: 100%;
}

.picker-content {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 10rpx;
}

.pet-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.pet-name {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.picker-arrow {
  font-size: 24rpx;
  color: #999;
}

.map-container {
  margin: 0 20rpx 20rpx;
  border-radius: 15rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.map {
  width: 100%;
  height: 400rpx;
}

.fence-section {
  background: #fff;
  margin: 0 20rpx 20rpx;
  border-radius: 15rpx;
  padding: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
  font-weight: bold;
}

.input {
  width: 100%;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
}

.coords-display {
  background: #f8f8f8;
  padding: 20rpx;
  border-radius: 8rpx;
}

.coord-text {
  display: block;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.radius-slider {
  margin: 20rpx 0;
}

.radius-value {
  font-size: 26rpx;
  color: #007AFF;
  font-weight: bold;
}

.alarm-options {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.alarm-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
}

.option-text {
  font-size: 26rpx;
  color: #333;
}

.fence-list {
  background: #fff;
  margin: 0 20rpx 20rpx;
  border-radius: 15rpx;
  padding: 30rpx;
}

.fence-item {
  border-bottom: 1px solid #f0f0f0;
  padding: 20rpx 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.fence-item:last-child {
  border-bottom: none;
}

.fence-info {
  flex: 1;
}

.fence-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 5rpx;
}

.fence-radius {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-bottom: 5rpx;
}

.fence-status {
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
}

.status-enabled {
  background: #D4EDDA;
  color: #155724;
}

.status-disabled {
  background: #F8D7DA;
  color: #721C24;
}

.fence-actions {
  display: flex;
  gap: 10rpx;
}

.action-btn {
  border: none;
  border-radius: 6rpx;
  padding: 10rpx 20rpx;
  font-size: 24rpx;
}

.edit {
  background: #007AFF;
  color: #fff;
}

.delete {
  background: #FF3B30;
  color: #fff;
}
</style>